import XLSX from 'xlsx';
import { importSave } from './api';
import { message } from '@/utils/util';

export default {
  name: 'price-base-goods-import-modal',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    topChannelList: {
      type: Array,
      default: () => [],
    },
  },

  data() {
    return {
      formValue: {
        topChannelCode: '',
        baseGoodsList: [],
      },
      stepNumber: 0,
      formRules: {
        topChannelCode: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (!this.formValue.topChannelCode) {
                callback('顶级渠道为空');
              } else {
                callback();
              }
            },
          },
        ],
        goods: [
          {
            required: true,
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.formValue.baseGoodsList.length === 0) {
                callback('导入信息为空');
              } else {
                callback();
              }
            },
          },
        ],
      },
      formLabelWidth: '300px',
      resultVisible: false,
      // tipData: [],
      importing: false,
    };
  },
  watch: {},
  methods: {
    async onSubmit(name) {
      this.$refs[name].validate(async valid => {
        if (valid) {
          try {
            this.stepNumber = 2;
            this.importing = true;
            await importSave(this.formValue);
            const { topChannelCode } = this.formValue;
            this.onClose();
            this.resetTable(topChannelCode);
            this.stepNumber = 3;
            message('提示', '导入成功', 'success');
          } catch (e) {
            message('错误', e.message, 'error');
          }
          this.importing = false;
        }
      });
    },
    resetTable(value) {
      this.$emit('resetTable', value);
    },
    onClose() {
      this.formValue = {};
      this.$refs.formRef.resetFields();
      this.$refs.upload.uploadFiles = [];
      this.$emit('close');
      this.stepNumber = 0;
    },
    onChange(file) {
      const reader = new FileReader();
      reader.onload = e => {
        let data = e.target.result;
        const workbook = XLSX.read(data, { type: 'buffer' });
        const [sheetName] = workbook.SheetNames;
        const sheetInfo = workbook.Sheets[sheetName];
        if (
          !sheetInfo.A1 ||
          sheetInfo.A1.v !== '商品编码' ||
          !sheetInfo.B1 ||
          sheetInfo.B1.v !== '分公司编码' ||
          !sheetInfo.C1 ||
          sheetInfo.C1.v !== '最低毛利率' ||
          !sheetInfo.D1 ||
          sheetInfo.D1.v !== '商品类型' ||
          !sheetInfo.E1 ||
          sheetInfo.E1.v !== '原价限购数量' ||
          !sheetInfo.F1 ||
          sheetInfo.F1.v !== '限购频率' ||
          !sheetInfo.G1 ||
          sheetInfo.G1.v !== '特价限购数量' ||
          !sheetInfo.H1 ||
          sheetInfo.H1.v !== '是否自动化调价'
        ) {
          message('提示', '模板格式错误', 'error');
          return;
        }
        const parsedSheetInfo = XLSX.utils.sheet_to_json(sheetInfo);
        const result = parsedSheetInfo.map((item, index) => ({
          rowNo: index + 1,
          companyCode: String(item['分公司编码'] || ''),
          goodsCode: String(item['商品编码'] || ''),
          minGross: String(item['最低毛利率']),
          goodsType: String(item['商品类型'] || ''),
          limitNum: String(item['原价限购数量']),
          limitFrequency: String(item['限购频率']),
          activityPriceLimit: String(item['特价限购数量']),
          autoPrice: String(item['是否自动化调价'] || ''),
        }));
        // message('提示', '文件上传成功', 'success');
        this.stepNumber = 1;
        console.log('result', result);
        if (result && result.length > 0) {
          const list = [];
          const isNotNext = result.some(item => {
            const { rowNo, companyCode, goodsCode, minGross, goodsType, limitNum, limitFrequency, activityPriceLimit, autoPrice } = item;
            const rowText = '第' + rowNo + '行';
            const obj = {};
            if (!companyCode) {
              message('提示', rowText + '分公司编码为空', 'warning');
              return true;
            } else {
              obj.companyCode = companyCode.trim();
            }
            if (!goodsCode) {
              message('提示', rowText + '商品编码为空', 'warning');
              return true;
            } else {
              obj.goodsCode = goodsCode.trim();
            }
            if (!goodsType) {
              message('提示', rowText + '商品类型为空', 'warning');
              return true;
            } else {
              obj.goodsType = goodsType.trim();
            }
            if (!autoPrice) {
              message('提示', rowText + '是否自动化调价为空', 'warning');
              return true;
            } else {
              obj.autoPrice = autoPrice.trim();
            }

            // // limitNum 原价限购数量
            const reg = /^(-1|\d+)$/; // 大于等于-1的数

            // const reg = /^([1-9]|[0-9]\d+)(\d{0})?$/;
            if (limitNum === 'undefined') {
              // message('提示', rowText + '原价限购数量为空', 'warning');
              // return true;
              obj.limitNum = null;
            } else if (!reg.test(limitNum)) {
              message('提示', rowText + '原价限购数量请填写大于等于-1的整数', 'warning');
              return true;
            } else {
              obj.limitNum = Number(limitNum);
            }

            // limitFrequency 限购频率
            if (limitFrequency === 'undefined') {
              // message('提示', rowText + '限购频率为空', 'warning');
              // return true;
              obj.limitFrequency = null;
            } else if (!reg.test(limitFrequency)) {
              message('提示', rowText + '限购频率请填写大于等于-1的整数', 'warning');
              return true;
            } else {
              obj.limitFrequency = Number(limitFrequency);
            }

            // 特价限购数量
            if (activityPriceLimit === 'undefined') {
              // message('提示', rowText + '特价限购数量为空', 'warning');
              // return true;
              obj.activityPriceLimit = null;
            } else if (!reg.test(activityPriceLimit)) {
              message('提示', rowText + '特价限购数量请填写大于等于-1的整数', 'warning');
              return true;
            } else {
              obj.activityPriceLimit = Number(activityPriceLimit);
            }

            // 最低毛利率
            const reg2 = /^(([-+])?[1-9][0-9]*)(\.\d{1,2})?$/;
            if (minGross === 'undefined') {
              // message('提示', rowText + '最低毛利率为空', 'warning');
              // return true;
              obj.minGross = null;
            } else if (!reg2.test(minGross)) {
              message('提示', rowText + '最低毛利率请填写最多2位小数的数字', 'warning');
              return true;
            } else {
              obj.minGross = Number(minGross);
            }
            list.push(obj);
          });
          if (isNotNext) {
            this.formValue.baseGoodsList = [];
            this.$refs.upload.clearFiles();
            return;
          }
          console.log('list', list);
          this.formValue.baseGoodsList = list;
          this.$refs.formRef.validateField('goods');
        } else {
          this.formValue.baseGoodsList = [];
        }
      };
      reader.readAsArrayBuffer(file.raw);
    },
    onError() {
      message('错误', '文件上传失败', 'error');
    },
    //模板下载
    downImportTemplate() {
      window.location.href = './docs/调价基础商品导入模板.xlsx';
    },
    onCloseResultModal() {
      this.resultVisible = false;
    },
  },
  mounted() {},
};
